package com.amazonaws.demo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.amazonaws.demo.sdb.SimpleDB;
import com.google.android.gms.location.LocationClient;
import com.twilio.sdk.TwilioRestClient;
import com.twilio.sdk.TwilioRestException;
import com.twilio.sdk.resource.factory.SmsFactory;
import com.twilio.sdk.resource.instance.Account;
import com.twilio.sdk.resource.instance.Sms;

public class Verification extends Activity {

	private static final String success = "Welcome to The AWS Browser Demo!";
	private static final String fail = "Load Failed. Please Try Restarting the Application.";
	private String TAG = "FUCK";

	protected Button verify;
	private Button reSend;
	private Button back;
	private EditText verificationCode;
	private EditText password;
	private boolean isValidUser;
	private Context context;

	private TextView Timer;

	public Handler myHandler;
	public static final String ACCOUNTSID = "ACa8cd84343d08f6f84fd3ca5b1c532751";
	public static final String AUTHTOKEN = "dd10c126da38021664352140c022b0a6";
	public static final int SEND_MESSAGE = 1;
	private int randomCode;
	public final int VERIFY_FINISHED = 1;
	public final int VERIFY_FAILED = 2;
	private LocationClient mLocationClient;
	public String logInName;
	public String passWord;
	public static AmazonClientManager clientManager = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.verification);
		// get the layout 
		context = this;
		verify = (Button) findViewById(R.id.verifyButton);
		reSend = (Button) findViewById(R.id.reSend);
		back = (Button) findViewById(R.id.backToRegister);
		logInName = getIntent().getExtras().getString("userPhoneNumber");
		passWord = getIntent().getExtras().getString("userPassword");

		clientManager = new AmazonClientManager();
		verificationCode = (EditText)findViewById(R.id.verificationCode);

		//		 new CountDownTimer(600000, 1000) {
		//
		//		     public void onTick(long millisUntilFinished) {
		//		         Timer.setText("seconds remaining: " + millisUntilFinished / 1000);
		//		     }
		//
		//		     public void onFinish() {
		//		    	 Toast.makeText(getApplicationContext(), "done!", Toast.LENGTH_SHORT).show();
		//		     }
		//		  }.start();

		verify.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences settings = getSharedPreferences("preference", 0);
				String code = ""+settings.getInt("verificationCode", 0000);
				if(code.equals(verificationCode.getText().toString())){
					Toast.makeText(getApplicationContext(), "registered successfully!", 
							Toast.LENGTH_SHORT).show();		
					Intent i = new Intent(Verification.this, map.class);
					i.putExtra("userName", logInName);
					startActivity(i);
					Thread thread = new Thread(new Runnable(){
						public void run(){
							setupDatabase();
						}
					});
					thread.start();
					



					//					String password =getIntent().getExtras().getString("userPassword");
					//					Toast.makeText(getApplicationContext(), "logInName = " + logInName, Toast.LENGTH_SHORT).show();

				}
			}
		});
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(Verification.this,newUser.class);
				startActivity(i);
				finish();
			}

		});
		reSend.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Thread thread = new Thread(new Runnable(){
					public void run(){
						SharedPreferences settings = getSharedPreferences("preference", 0);

						if(checkSendMsg()){
							sendTextMessage();
						}else{

							runOnUiThread(new Runnable(){
								public void run(){
									SharedPreferences settings = getSharedPreferences("preference", 0);

									Toast.makeText(getApplicationContext(), "Please wait for " + (Math.pow(10, settings.getInt("msgCounter", 0) - 2) - 
											System.currentTimeMillis() / 60000 +  settings.getLong("lastTimeSendMsg", 0)/60000) + " mins to register again.", 
											Toast.LENGTH_SHORT).show();
								}
							});
						}
					}
				});
				thread.start();	
			}

		});

	}

	public boolean checkSendMsg(){
		SharedPreferences settings = getSharedPreferences("preference", 0);
		Log.d("ffffffkkkkkkk",   "Mins since last time send msg " +(System.currentTimeMillis() - settings.getLong("lastTimeSendMsg", 0)) / 60000 + ""   );
		Log.d("ffffffkkkkkkk",   "counter before " + settings.getInt("msgCounter", 0) + ""   );
		if(!settings.contains("lastTimeSendMsg")){		
			SharedPreferences.Editor editor = settings.edit();
			editor.putInt("msgCounter", 0);
			editor.putLong("lastTimeSendMsg", System.currentTimeMillis());
			editor.commit();
		}

		if(settings.getInt("msgCounter", 0) < 2){
			SharedPreferences.Editor editor = settings.edit();
			editor.putInt("msgCounter", settings.getInt("msgCounter", 0) + 1);
			editor.putLong("lastTimeSendMsg", System.currentTimeMillis());
			editor.commit();
			return true;
		}else{
			if((System.currentTimeMillis() - settings.getLong("lastTimeSendMsg", 0)) / 60000 < Math.pow(10, settings.getInt("msgCounter", 0) -2)  ){
				return false;
			}else{

				SharedPreferences.Editor editor = settings.edit();
				editor.putInt("msgCounter", settings.getInt("msgCounter", 0) + 1);
				editor.putLong("lastTimeSendMsg", System.currentTimeMillis());
				editor.commit();
				return true;
			}
		}
	}


	public void sendTextMessage(){
		Random randomGenerator = new Random(System.currentTimeMillis());
		randomCode = randomGenerator.nextInt(10000);

		SharedPreferences settings = getSharedPreferences("preference", 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt("verificationCode", randomCode);
		editor.commit();
		/* Instantiate a new Twilio Rest Client */
		TwilioRestClient client = new TwilioRestClient(ACCOUNTSID, AUTHTOKEN);

		// Get the account and call factory class
		Account acct = client.getAccount();
		SmsFactory smsFactory = acct.getSmsFactory();

		String fromNumber = "425-728-7464";
		Map<String,String> params = new HashMap<String,String>();
		params.put("From", fromNumber);
		params.put("To", "2066608173");
		params.put("Body", "Ahoy from E2gether! your verification number is "+ randomCode);

		try {
			// send an sms a call  
			// ( This makes a POST request to the SMS/Messages resource)
			Sms sms = smsFactory.create(params);
		}
		catch (TwilioRestException e) {
			e.printStackTrace();
		}
	}

	public void setupDatabase(){
		//SimpleDB.createAttributeForItem( "wuyueLocation", "location", "lat",mLocationClient.getLastLocation().getLatitude() + "");
		//SimpleDB.createAttributeForItem( "wuyueLocation", "location", "long",mLocationClient.getLastLocation().getLongitude() + "");
		SimpleDB.createDomain( logInName );
		
		
		SimpleDB.createItem( logInName, "passwordItem"); 
		HashMap<String, String> password = new HashMap<String,String>();
		password.put("userPassword", passWord);
		SimpleDB.updateAttributesForItem(logInName, "passwordItem", password);
		
		
		SimpleDB.createItem( logInName, "locationItem"); 
		HashMap<String, String> myLocation = new HashMap<String,String>();
		myLocation.put("lat", "");
		myLocation.put("long","");
		SimpleDB.updateAttributesForItem(logInName, "locationItem", myLocation);
		//create user's Nickname
		SimpleDB.createItem(logInName,"nickNameItem");
		HashMap<String, String> userNickname = new HashMap<String,String>();
		userNickname.put("userNickname", "");
		SimpleDB.updateAttributesForItem(logInName, "nickNameItem", userNickname);
		//create time item
		SimpleDB.createItem(logInName,"timeItem");
		HashMap<String, String> myTime = new HashMap<String,String>();
		myTime.put("startHour", "");
		myTime.put("endHour", "");
		myTime.put("startMin", "");
		myTime.put("endMin", "");
		SimpleDB.updateAttributesForItem(logInName, "timeItem", myTime);
		//create range item
		SimpleDB.createItem(logInName,"rangeItem");
		HashMap<String, String> myRange = new HashMap<String,String>();
		myRange.put("range", "");
		SimpleDB.updateAttributesForItem(logInName, "rangeItem", myRange);
		//create say something
		SimpleDB.createItem(logInName,"saySthItem");
		HashMap<String, String> mysaySth = new HashMap<String,String>();
		mysaySth.put("status", "");
		SimpleDB.updateAttributesForItem(logInName, "saySthItem", mysaySth);
		
		//create list of friends thats you have sent request to 
		//the hash map's key will be the phone numbers that you have send request to, the value of
		//each key is defaulted to be ""!!!!!
		SimpleDB.createItem(logInName, "sentFriendRequestItem");
		HashMap<String,String> sentFriendRequest = new HashMap<String,String>();
//		sentFriendRequest.put("sentToOther", "");
		SimpleDB.updateAttributesForItem(logInName, "sentFriendRequestItem", sentFriendRequest);
//		
		//create list of friends you have received request from
		SimpleDB.createItem(logInName, "receivedFriendRequestItem");
		HashMap<String,String> requestList = new HashMap<String,String>();
//		requestList.put("requestFromOthers", "");
		SimpleDB.updateAttributesForItem(logInName, "receivedFriendRequestItem", requestList);
		
		//actual friend list: the key set are the friend list, every key map to an EMPTY STRING!!!!!
		SimpleDB.createItem(logInName, "friendListItem");
		HashMap<String,String> friendList = new HashMap<String,String>();
//		friendList.put("friendList", "");
		SimpleDB.updateAttributesForItem(logInName, "friendListItem", friendList);
	}


}
